﻿using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace echuCMS
{
    public partial class FormCustomerPotential : Form
    {
        
        BindingSource bsCustomerMain = new BindingSource();
        BindingSource bsSalesMan = new BindingSource();
        BindingSource bsDistributionResult = new BindingSource();
        Dictionary<SalesMan, List<CustomerMain>> dic_sal_cus = new Dictionary<SalesMan, List<CustomerMain>>();
        public FormCustomerPotential()
        {
            InitializeComponent();
        }

        private void FormCustomerPotential_Load(object sender, EventArgs e)
        {
            dataGridViewCustormer.AutoGenerateColumns = false;
            dataGridViewSalesMan.AutoGenerateColumns = false;
            dataGridViewDistributionResult.AutoGenerateColumns = false;
        }
        private void FormCustomerPotential_Shown(object sender, EventArgs e)
        {
            //加载所有公共池客户
            bsCustomerMain.DataSource = getAllCustomerMainNotInPotentialAndBlack();
            this.dataGridViewCustormer.DataSource = bsCustomerMain;
            //加载所有业务员及其已经分配的客户
            bsSalesMan.DataSource = getAllSalesManWithTotalCustomerPotential();
            this.dataGridViewSalesMan.DataSource = bsSalesMan;
        }

        private List<CustomerMain> getAllCustomerMainNotInPotentialAndBlack()
        {
            return CustomerMainService.getAllCustomerMainNotInPotentialAndBlack();
        }

        /// <summary>
        /// 查询所有客户
        /// </summary>
        /// <returns></returns>
        private List<CustomerMain> getAllCustomerMain()
        {
            return CustomerMainService.getAllCustomerMain();
        }
        /// <summary>
        /// 查询所有业务员及已经分配的公共池客户
        /// </summary>
        /// <returns></returns>
        private List<SalesMan> getAllSalesManWithTotalCustomerPotential()
        {
            return SalesManService.getAllSalesManWithTotalCustomerPotential();
        }
        /// <summary>
        /// 将未分配的客户平均分配给业务员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDivDistribut_Click(object sender, EventArgs e)
        {
            //没有设置每个业务员分配几个客户或最多几个客户
            if (string.IsNullOrEmpty(textBoxToalCus.Text.Trim()) && string.IsNullOrEmpty(textBoxMaxCus.Text.Trim())
                && bsCustomerMain.Count >= bsSalesMan.Count)
            {
                //有多少业务员
                int salesManAmount = bsSalesMan.Count;
                //有多少客户
                int customerAmount = bsCustomerMain.Count;
                //计算平均每个业务员可以跟多少个客户(取整数)
                int  divAmount = Convert.ToInt32(Math.Floor(Convert.ToDecimal(customerAmount / salesManAmount)));
                //默认最多20,超过20就只分配20个
                if (divAmount > 20)
                {
                    divAmount = 20;
                }
                //根据计算的平均一个业务员多少客户的个数进行分组
                List<List<CustomerMain>> listGroup = new List<List<CustomerMain>>();

                for (int i = 0; i < bsCustomerMain.Count; i += divAmount)
                {
                    List<CustomerMain> cList = new List<CustomerMain>();
                    cList = (bsCustomerMain.DataSource as List<CustomerMain>).Skip(i).Take(divAmount).ToList();//take为每次取的数量，skip为跳过的数量。执行时take每次取0~9，skip跳过i项。
                    //j += Convert.ToInt32(divAmount);
                    listGroup.Add(cList);
                }

                //再把分组后的客户，赋值给业务员
                if (listGroup.Count == salesManAmount)
                {
                    for (int i = 0; i < bsSalesMan.Count; i++)
                    {
                        (bsSalesMan[i] as SalesMan).customerMainList = listGroup[i];
                    }
                }
                else
                {
                    MessageBox.Show("客户分组数量与业务员人数不符合");
                }

                //显示默认选中业务员的客户
                if (bsSalesMan.Current != null)
                {
                    bsDistributionResult.DataSource = (bsSalesMan.Current as SalesMan).customerMainList;
                    dataGridViewDistributionResult.DataSource = bsDistributionResult;
                }
            }
        }
        /// <summary>
        /// 点击业务员，显示分配到的客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewSalesMan_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                bsDistributionResult.DataSource = (bsSalesMan.Current as SalesMan).customerMainList;
                dataGridViewDistributionResult.DataSource = bsDistributionResult;
                bsDistributionResult.ResetBindings(true);
            }
        }
        /// <summary>
        /// 取消这个客户的分配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCancleOneDistribute_Click(object sender, EventArgs e)
        {
            if (dataGridViewDistributionResult.SelectedRows.Count < 1)
            {
                MessageBox.Show("请选择一个需要取消分配的客户");
            }
            else
            {
                //把当前客户返回给公共池
                bsCustomerMain.Add(Pub.DeepCopyByBin(bsDistributionResult.Current));
                bsCustomerMain.ResetBindings(true);
                bsDistributionResult.RemoveCurrent();
            }
        }
        /// <summary>
        /// 取消所有的分配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCancleAllDistribute_Click(object sender, EventArgs e)
        {
            List<SalesMan> salesMen = bsSalesMan.DataSource as List<SalesMan>;
            if (salesMen != null && salesMen.Count > 0)
            {
                foreach (var item in salesMen)
                {
                    if (item.customerMainList != null)
                    {
                        foreach (var it in item.customerMainList)
                        {
                            bsCustomerMain.Add(Pub.DeepCopyByBin(it));
                        }
                        item.customerMainList.Clear();
                    }
                    
                }
                bsDistributionResult.DataSource = null;
            }
            bsCustomerMain.ResetBindings(true);
        }

        private void buttonCancelSalesManDistribute_Click(object sender, EventArgs e)
        {
            if (bsSalesMan.Current == null && dataGridViewSalesMan.SelectedRows.Count < 1)
            {
                MessageBox.Show("请选择一个需要取消分配的业务员");
            }
            else
            {
                if ((bsSalesMan.Current as SalesMan).customerMainList != null)
                {
                    for (int i = 0; i < (bsSalesMan.Current as SalesMan).customerMainList.Count; i++)
                    {
                        bsCustomerMain.Add(Pub.DeepCopyByBin((bsSalesMan.Current as SalesMan).customerMainList[i]));
                    }
                    (bsSalesMan.Current as SalesMan).customerMainList.Clear();
                }
                bsDistributionResult.ResetBindings(true);
            }
            bsCustomerMain.ResetBindings(true);
        }
        /// <summary>
        /// 优先分配分数高的业务员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSalesManMaxScoreFirt_Click(object sender, EventArgs e)
        {
            List<SalesMan> salesMen = bsSalesMan.DataSource as List<SalesMan>;
            List<CustomerMain> customerMainList = bsCustomerMain.DataSource as List<CustomerMain>;
            int salesmanMaxCus = 0;
            if (int.TryParse(textBoxMaxCus.Text.Trim(), out salesmanMaxCus))
            {

            }
            else
            {
                salesmanMaxCus = 20;//默认分配20个
            }
            distribute(salesMen,customerMainList,0,salesmanMaxCus);
            ////遍历业务员（已经根据分数从高到底排序查询，所以遍历的也是分数从高到低）
            //if (bsSalesMan.DataSource != null && bsSalesMan.Count > 0)
            //{
            //    //表格业务员数据源转换为list
            //    List<SalesMan> salesMen = bsSalesMan.DataSource as List<SalesMan>;
            //    List<CustomerMain> customerMainList = bsCustomerMain.DataSource as List<CustomerMain>;
            //    //如果业务员不为空
            //    if (salesMen != null && salesMen.Count > 0)
            //    {
            //        foreach (var salesMan in salesMen)
            //        {
            //            if (salesMan.TotalCustomerPotential < 4)//这个业务员没分配满20个，则继续分配
            //            {
            //                //如果还没分配，customerMainList为null，则new一个
            //                if (salesMan.customerMainList == null)
            //                {
            //                    salesMan.customerMainList = new List<CustomerMain>();
            //                }
            //                //需要分配的数量 = 默认分配数量-已经分配数量-前端当前已经分配数量
            //                //计算还差几个才满20个
            //                int needToDistributeAmount = 3 - salesMan.TotalCustomerPotential - salesMan.customerMainList.Count;
            //                //如果需要分配个数为0则不分配
            //                if (needToDistributeAmount<=0)
            //                {
            //                    continue;
            //                }
            //                //如果公共池客户数只够分给这个业务员,则全部分配给他
            //                if (customerMainList != null && customerMainList.Count > 0)
            //                {
            //                    for (int i = 0; i < customerMainList.Count; i++)
            //                    {
            //                        //如果不是已经分配过且没有成交返回了公共池的客户则给这个业务员
            //                        if (salesMan.deadcustomerMainList.Find(it => it.CustomerCode == customerMainList[i].CustomerCode) == null)
            //                        {
            //                            salesMan.customerMainList.Add(Pub.DeepCopyByBin(customerMainList[i]));
            //                            customerMainList.Remove(customerMainList[i]);
            //                            //下标回退1，因为已经把当前的公共池客户移除了
            //                            i--;
            //                            if (salesMan.customerMainList.Count == needToDistributeAmount)
            //                            {
            //                                break;
            //                            }
            //                        }  
            //                    }
            //                    //customerMainList.Clear();
            //                    bsCustomerMain.ResetBindings(true);
            //                    //break;
            //                }
            //如果公共池客户数超过这个业务员需要分配的数量，则根据缺少的数量分配（要检查有没有分配给过他）
            //if (customerMainList != null && customerMainList.Count > needToDistributeAmount)
            //else
            //{
            //    //如果待分配的客户数大于应分配的就向下查询
            //    List<CustomerMain> customerDistribute = new List<CustomerMain>();
            //    //foreach (var customerMain in customerMainList)
            //    for (int i = 0; i < customerMainList.Count; i++)
            //    {
            //        //如果不是已经分配过且没有成交返回了公共池的客户则给这个业务员
            //        if (salesMan.deadcustomerMainList.Find(it => it.CustomerCode == customerMainList[i].CustomerCode) == null)
            //        {
            //            //把这个客户分配给这个业务员
            //            customerDistribute.Add(Pub.DeepCopyByBin(customerMainList[i]));
            //            //从从共池移除
            //            customerMainList.Remove(customerMainList[i]);
            //            //下标回退1，因为已经把当前的公共池客户移除了
            //            i--;
            //            bsCustomerMain.ResetBindings(true);
            //            //如果公共池客户遍历还没结束，但是待分配个数正好是需要分配的个数则结束给这个业务员分配
            //            if (customerDistribute.Count == needToDistributeAmount)
            //            {
            //                break;
            //            }
            //        }
            //    }
            //    salesMan.customerMainList = customerDistribute;
            //}
            //            }
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 分配客户
        /// </summary>
        /// <param name="salesManList">所有业务员</param>
        /// <param name="customerMainList">所有待分配客户</param>
        /// <param name="salesmanToalCus">业务员总共分配多少个</param>
        /// <param name="salesmanMaxCus">业务员最大分配多少个</param>
        private void distribute(List<SalesMan> salesManList, List<CustomerMain> customerMainList,int salesmanToalCus,int salesmanMaxCus)
        {
            //遍历业务员（已经根据分数从高到底排序查询，所以遍历的也是分数从高到低）
            //if (bsSalesMan.DataSource != null && bsSalesMan.Count > 0)
            //{
                //表格业务员数据源转换为list
                //如果业务员不为空
                if (salesManList != null && salesManList.Count > 0)
                {
                    foreach (var salesMan in salesManList)
                    {
                        if (salesMan.TotalCustomerPotential <= salesmanMaxCus)//这个业务员没分配满20个，则继续分配
                        {
                            //如果还没分配，customerMainList为null，则new一个
                            if (salesMan.customerMainList == null)
                            {
                                salesMan.customerMainList = new List<CustomerMain>();
                            }
                            //需要分配的数量 = 默认分配数量-已经分配数量-前端当前已经分配数量
                            //计算还差几个才满20个
                            int needToDistributeAmount = salesmanMaxCus - salesMan.TotalCustomerPotential - salesMan.customerMainList.Count;
                            //如果需要分配个数为0则不分配
                            if (needToDistributeAmount <= 0)
                            {
                                continue;
                            }
                            //如果公共池客户数只够分给这个业务员,则全部分配给他
                            if (customerMainList != null && customerMainList.Count > 0)
                            {
                                for (int i = 0; i < customerMainList.Count; i++)
                                {
                                    //如果不是已经分配过且没有成交返回了公共池的客户则给这个业务员
                                    if (salesMan.deadcustomerMainList.Find(it => it.CustomerCode == customerMainList[i].CustomerCode) == null)
                                    {
                                        salesMan.customerMainList.Add(Pub.DeepCopyByBin(customerMainList[i]));
                                        customerMainList.Remove(customerMainList[i]);
                                        //下标回退1，因为已经把当前的公共池客户移除了
                                        i--;
                                        if (salesMan.customerMainList.Count == needToDistributeAmount)
                                        {
                                            break;
                                        }
                                    }
                                }
                                //customerMainList.Clear();
                                bsCustomerMain.ResetBindings(true);
                                //break;
                            }
                            //如果公共池客户数超过这个业务员需要分配的数量，则根据缺少的数量分配（要检查有没有分配给过他）
                            //if (customerMainList != null && customerMainList.Count > needToDistributeAmount)
                            //else
                            //{
                            //    //如果待分配的客户数大于应分配的就向下查询
                            //    List<CustomerMain> customerDistribute = new List<CustomerMain>();
                            //    //foreach (var customerMain in customerMainList)
                            //    for (int i = 0; i < customerMainList.Count; i++)
                            //    {
                            //        //如果不是已经分配过且没有成交返回了公共池的客户则给这个业务员
                            //        if (salesMan.deadcustomerMainList.Find(it => it.CustomerCode == customerMainList[i].CustomerCode) == null)
                            //        {
                            //            //把这个客户分配给这个业务员
                            //            customerDistribute.Add(Pub.DeepCopyByBin(customerMainList[i]));
                            //            //从从共池移除
                            //            customerMainList.Remove(customerMainList[i]);
                            //            //下标回退1，因为已经把当前的公共池客户移除了
                            //            i--;
                            //            bsCustomerMain.ResetBindings(true);
                            //            //如果公共池客户遍历还没结束，但是待分配个数正好是需要分配的个数则结束给这个业务员分配
                            //            if (customerDistribute.Count == needToDistributeAmount)
                            //            {
                            //                break;
                            //            }
                            //        }
                            //    }
                            //    salesMan.customerMainList = customerDistribute;
                            //}
                        }
                    }
                //}
            }
        }
        /// <summary>
        /// 保存分配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSaveDistribute_Click(object sender, EventArgs e)
        {
            
            List<SalesMan> salesMen = bsSalesMan.DataSource as List<SalesMan>;
            //如果业务员不为空
            if (salesMen != null && salesMen.Count > 0)
            {
                //公共池客户转换为潜在客户
                List<CustomerPotential> customerPotentialList = new List<CustomerPotential>();
                //潜在客户——业务员中间表
                List<PotentialSalesman> potentialSalesmanList = new List<PotentialSalesman>();
                foreach (var salesMan in salesMen)
                {
                    //如果有分配了公共池客户
                    if (salesMan.customerMainList != null && salesMan.customerMainList.Count > 0)
                    {
                        foreach (var customerMain in salesMan.customerMainList)
                        {
                            //将公共池客户转为潜在客户表
                            CustomerPotential customerPotential = new CustomerPotential();
                            customerPotential.Id = Guid.NewGuid().ToString();
                            customerPotential.CustomerMainId = customerMain.Id;
                            customerPotential.Status = 1;
                            customerPotential.CreateTime = DateTime.Now;
                            customerPotentialList.Add(customerPotential);
                            //将潜在客户id和业务员id插入中间表
                            PotentialSalesman potentialSalesman = new PotentialSalesman();
                            potentialSalesman.Id = Guid.NewGuid();
                            potentialSalesman.PotentialId = customerPotential.Id;
                            potentialSalesman.SalesManId = salesMan.Id;
                            potentialSalesman.Status = 1;
                            potentialSalesman.CreateTime = DateTime.Now;
                            potentialSalesmanList.Add(potentialSalesman);
                        }
                    }
                }
                //执行将公共池客户转到潜在客户
                int i = CustomerMainService.transferCustomerMainToPotential(customerPotentialList, potentialSalesmanList);
                if (i>0)
                {
                    MessageBox.Show("分配成功");
                    buttonSaveDistribute.Enabled = false;
                }
                else
                {
                    MessageBox.Show("分配失败，请联系开发者");
                }
            }
           

            
        }

        private void dataGridViewCustormer_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && dataGridViewCustormer.Columns[e.ColumnIndex].Name == "C单独分配")
            {
                //单据分配
                CustomerMain customerMain = bsCustomerMain.Current as CustomerMain;
                FormDistributeCustomerToTheSalesMan formDistributeCustomerToTheSalesMan = new FormDistributeCustomerToTheSalesMan(customerMain);
                formDistributeCustomerToTheSalesMan.ShowDialog();
            }
        }
    }
}
